package com.cloud.logger.zchain.core.zookeeper;

import com.cloud.logger.zchain.core.common.properties.ServerInfo;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.zookeeper.CreateMode;

/**
 * Created by Administrator on 2017/12/17.
 */
public class ZchainConnectionStateListener implements ConnectionStateListener {
    private String path;
    private String data;

    public ZchainConnectionStateListener(String path, String data) {
        this.path = path;
        this.data = data;
    }

    @Override
    public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
        System.out.println("Server:"+ ServerInfo.ip+"connectionState"+connectionState);
        if (connectionState == ConnectionState.RECONNECTED) {
            while (true) {
                try {
                    if (curatorFramework.getZookeeperClient().blockUntilConnectedOrTimedOut()) {
                        curatorFramework.create().
                                creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).
                                forPath(path, data.getBytes());
                        break;
                    }
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                }
            }
        }
    }
}
